package com.warthur.spring.shiro.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author warthur
 * @date 2018/09/09
 */
public class JwtUtils {

    public static final long EXPIRE_TIME = 2 * 3600 * 1000;
    public static final String JWT_AUTH_ID = "JWT_AUTH_ID";
    private static final String SIGN_SECRET = "a036692d9cc18ea29d94f634aaaca197";

    public static String token(String userName) {
        Map<String, Object> claimMap = new HashMap<>(1);
        claimMap.put("userName", userName);
        return Jwts.builder()
                .setId(JWT_AUTH_ID)
                .setClaims(claimMap)
                .setSubject(userName)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS512, SIGN_SECRET)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                .compact();
    }

    public static boolean verify(String token, Object userName) {
        return Jwts.parser()
                .setSigningKey(SIGN_SECRET)
                .parseClaimsJws(token)
                .getBody().getSubject().equals(userName);
    }

    public static Object getClaim(String token) {
        return Jwts.parser()
                .setSigningKey(SIGN_SECRET)
                .parseClaimsJws(token).getBody().get("userName");
    }
}
